package cn.hyh.core.component;

import cn.hyh.core.pojo.User;
import cn.hyh.core.service.ServiceInterface.UserService;
import cn.hyh.core.service.impl.UserServiceImpl;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @auther :hyh
 * @desc :    认证  授权
 * @date :2019/7/11
 */

public class MyShiroRealm  extends AuthorizingRealm {

    @Autowired
    private UserService userService;
//     授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User user= (User) principalCollection.getPrimaryPrincipal();
        if (StringUtils.isNotEmpty(user.getTag())) {
              authorizationInfo.addRole(user.getTag());  //添加权限。
        }
        System.out.println("调用了权限认证的方法");
        return authorizationInfo;

    }

//    认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        char[] chars = (char[]) authenticationToken.getCredentials();
        String password =  new String(chars);
          //base64 编码。

         User  user=userService.findUser(username.substring(1), password);
        if (user != null) {
            user.setTag("admin");
            AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user,user.getPassword(),getName());
            Session session = SecurityUtils.getSubject().getSession();
            System.out.println(session);
            if (session != null) {
                session.setAttribute("user", user);
            }
            userService.update(user.setLastLogin(new Date()));
            return authenticationInfo;
        }
        return null;
    }
}
